package com.string.actortv.util;

import android.util.Log;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.string.actortv.dto.MovieInfo;
import com.string.actortv.dto.MovieList;
import com.string.actortv.dto.MovieTypeList;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import static com.string.actortv.util.CacheHelper.CACHE;

public class Bde4Util {

    private static final String BASE_URL = "https://bde4.com";
    private static final String BASE_PAGE_URL = "https://bde4.com/s/all/";
    private static final String BASE_TYPE_URL = "https://bde4.com/s/all";
    private static final String BASE_SEARCH_URL = "https://bde4.com/search/";
    private static final String BASE_PLAY_URL = "https://bde4.com/god/";

    public interface MovieTypeCallBack {
        void execute(List<MovieTypeList> movieTypeList);
    }

    public static void getMovieTypeAsync(MovieTypeCallBack callBack) {
        MyHttpUtil.getAsync(BASE_TYPE_URL, html -> {
            Document document = Jsoup.parse(html);
            List<MovieTypeList> movieTypeLists = new ArrayList<>();
            Elements aElements = document.getElementsByClass("container").get(1)
                    .getElementsByTag("dl").get(1)
                    .getElementsByTag("dd").get(0)
                    .getElementsByTag("a");
            for (Element a : aElements) {
                MovieTypeList movieTypeList = new MovieTypeList(a.text(), a.attr("href").split("/")[2].split(";")[0]);
                movieTypeLists.add(movieTypeList);
            }
            callBack.execute(movieTypeLists);
        }, null);
    }

    public interface MovieUrlCallBack {
        void execute(String playUrl, String cookie);
    }

    public static void getMovieUrlAsync(String pageUrl, MovieUrlCallBack callBack) {
        MyHttpUtil.getAsync(pageUrl, html -> {
            int beginIndex = html.indexOf("ptoken = \"") + 10;
            int endIndex = html.indexOf("\"", beginIndex);
            String ptoken = html.substring(beginIndex, endIndex);
            MyHttpUtil.getAsync(BASE_PLAY_URL + ptoken + "?sg=", urlJson -> {
                Log.d("urlJson", urlJson);
                String playUrl = JSONObject.parseObject(urlJson).getString("url") + "/" + System.currentTimeMillis() + ".mp4";
                String cookie = JSONObject.parseObject(urlJson).getString("cookie");
                Log.d("playUrl", playUrl);
                callBack.execute(playUrl, cookie);
            }, null);
        }, null);
    }

    public interface MovieListCallBack {
        void execute(List<MovieList> movieList);
    }

    public static void getMovieListAsync(int pageNo, String searchStr,
                                         String type, MovieListCallBack movieListCallBack) {
        String pageUrl;
        if (StrUtil.isEmpty(searchStr)) {
            if (StrUtil.isEmpty(type)) {
                pageUrl = BASE_PAGE_URL + pageNo;
            } else {
                pageUrl = BASE_URL + "/s/" + type + "/" + pageNo;
            }
        } else {
            pageUrl = BASE_SEARCH_URL + URLEncoder.encode(searchStr) + "/" + pageNo;
        }
        if (CACHE.containsKey(pageUrl)
                && CACHE.get(pageUrl) != null) {
            getList(pageUrl, searchStr, CACHE.get(pageUrl).toString(), movieListCallBack);
        } else {
            MyHttpUtil.getAsync(pageUrl, result -> {
                getList(pageUrl, searchStr, result, movieListCallBack);
            }, null);
        }
    }

    private static void getList(String pageUrl, String searchStr,
                                String html, MovieListCallBack movieListCallBack) {
        if ("".equals(html)) {
            Log.d("Bde4GetList", html);
            movieListCallBack.execute(null);
            return;
        }
        CACHE.put(pageUrl, html);
        Document document = Jsoup.parse(html);
        List<MovieList> movieList = new ArrayList<>();
        //获取当前电影列表
        Elements movieElements = document
                .getElementsByClass("cards")
                .get(0).getElementsByClass("card");
        if (movieElements != null) {
            for (Element movieElement : movieElements) {
                Elements elements = movieElement.getElementsByTag("a");
                if (!elements.isEmpty()) {
                    String name;
                    if (StrUtil.isNotEmpty(searchStr)) {
                        name = movieElement.getElementsByClass("header").get(0).attr("title");
                    } else {
                        name = elements.get(0).attr("title");
                    }
                    String img = elements.get(0).getElementsByTag("img").attr("src");
                    String url = BASE_URL + elements.get(0).attr("href").split(";")[0];
                    movieList.add(new MovieList(name, url, img));
                }
            }
        }
        movieListCallBack.execute(movieList);
    }

    public interface MovieInfoCallBack {
        void execute(MovieInfo movieInfo);
    }

    public static void getMovieInfoAsync(String href, String name, MovieInfoCallBack movieInfoCallBack) {
        //获取电影集数列表
        if (CACHE.containsKey(href)
                && CACHE.get(href) != null) {

            getInfo(name, CACHE.get(href).toString(), movieInfoCallBack);
        } else {
            MyHttpUtil.getAsync(href, movieHtml -> {
                if ("".equals(movieHtml)) {
                    movieInfoCallBack.execute(null);
                    return;
                }
                CACHE.put(href, movieHtml);

                getInfo(name, movieHtml, movieInfoCallBack);
            }, null);
        }
    }

    private static void getInfo(String name, String movieHtml, MovieInfoCallBack movieInfoCallBack) {
        Document document = Jsoup.parse(movieHtml);
        Elements descElements = document.getElementsByClass("summary");
        String desc = "";
        if (!descElements.isEmpty()) {
            desc = descElements.get(0).text();
        }
        Elements listElements = document
                .getElementsByClass("secondary");
        List<MovieInfo.SeasonList> seasonList = new ArrayList<>();
        if (listElements != null && !listElements.isEmpty()) {
            for (Element seasonElement : listElements) {
                String seasonName = seasonElement.text();
                String url = BASE_URL + seasonElement.attr("href").split(";")[0];

                seasonList.add(new MovieInfo.SeasonList(seasonName, url));
            }
        }
        movieInfoCallBack.execute(new MovieInfo(name, "", desc, seasonList));
    }

}
